package com.cea.papyrus.diagram.statemachine.helper;

import org.eclipse.uml2.uml.ChangeEvent;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.LiteralString;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.PackageableElement;
import org.eclipse.uml2.uml.UMLFactory;

import com.cea.papyrus.core.helper.NodeHelper;
import com.cea.papyrus.core.utils.Debug;
import com.cea.papyrus.diagraminterchange2.di2.GraphElement;

public class NodeChangeEventHelper extends NodeHelper {

	/**
	 * The channel.
	 */
	private int channel = 501;

	/**
	 * The default constructor.
	 */
	public NodeChangeEventHelper(){
		super();
		Debug.debug(this,"Call NodeChangeEventHelper()", channel);
	}

	@Override
	public boolean canCreateUMLElement(Element umlParent){
		Debug.debug(this,"Call boolean NodeChangeEventHelper.canCreateUMLElement(Element umlParent)", channel);
		if(umlParent instanceof Package)
			return true;
		return false;
	}

	@Override
	public boolean canCreateGraphElement(GraphElement parent) {
		return false;
	}
	
	@Override
	public Element createUMLElement(String name, Element umlParent){
		Debug.debug(this,"Call Element NodeChangeEventHelper.createUMLElement(String name, Element umlParent)", channel); //$NON-NLS-1$
		ChangeEvent event = UMLFactory.eINSTANCE.createChangeEvent();
		event.setName(name);
		LiteralString ls = UMLFactory.eINSTANCE.createLiteralString();
		ls.setValue("");
		event.setChangeExpression(ls);
		((Package)umlParent).getPackagedElements().add(event);
		return event;
	}

	@Override
	public boolean addUMLElement(Element element, Element umlParent){
		Debug.debug(this,"Call Element NodeChangeEventHelper.addUMLElement(element element, Element umlParent)", channel); //$NON-NLS-1$
		if(umlParent instanceof Package)
			return ((Package)umlParent).getPackagedElements().add((PackageableElement)element);
		return false;
	}
	
	@Override
	public boolean removeUMLElement(Element element, Element umlParent) {
		Debug.debug(this,"Call Element NodeChangeEventHelper.removeUMLElement(element element, Element umlParent)", channel); //$NON-NLS-1$
		if(umlParent instanceof Package)
			return ((Package)umlParent).getPackagedElements().remove(element);
		return false;
	}

	@Override
	public String getBaseString() {
		return "ChangeEvent_";
	}
	
	@Override
	public String getNewUMLElementName(Element umlParent){
		String name = ""; //$NON-NLS-1$

		//i <10000: avoid infinite loops
		for(int i=0; i< 10001; i++ ) {
			name = getBaseString()+i;
			if(umlParent == null)
				return name;
			else if(umlParent instanceof Package){
				if(((Package)umlParent).getPackagedElement(name) == null)
					return name;
			}
			else
				return name;
		}
		return getBaseString()+"X"; //$NON-NLS-1$
	}

}
